package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.user.constant.UserConstant;
import com.tvunetworks.center.user.controller.feign.UserFeignController;
import com.tvunetworks.center.user.mapper.BookmarkDeviceMapper;
import com.tvunetworks.center.user.mapper.UserBookmarkMapper;
import com.tvunetworks.center.user.mapper.UserMapper;
import com.tvunetworks.center.user.model.*;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.AlreadyShareSonListVo;
import com.tvunetworks.center.user.model.vo.UpdateBookMarkShareParam;
import com.tvunetworks.center.user.model.vo.UserBookmarkVo;
import com.tvunetworks.center.user.service.BookmarkDeviceService;
import com.tvunetworks.center.user.service.UserBookmarkService;
import com.tvunetworks.center.user.service.UserFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static com.tvunetworks.center.common.util.ResultUtil.success;

/**
 * @program: tvucc-user
 * @description: UserBookmarkServiceImpl
 * @author lebronchen
 * @create: 2019-03-14 15:36
 **/
@Service
public class UserBookmarkServiceImpl implements UserBookmarkService {

    @Autowired
    private UserBookmarkMapper userBookmarkMapper;
    @Autowired
    private BookmarkDeviceService bookmarkDeviceService;
    @Autowired
    private BookmarkDeviceMapper bookmarkDeviceMapper;
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private UserFeignController userFeignController;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<String> getAllChildBookmarkIds(String userId, String bookmarkIds) {
        if (StringUtils.isBlank(bookmarkIds)) {
            return null;
        }
        Set<String> resultSet = new HashSet<>();
        String[] bookmarkArr = bookmarkIds.split(",");
        resultSet.addAll(Arrays.asList(bookmarkArr));
        for (String bookmarkId : bookmarkArr) {
            List<UserBookmarkVo> bookmarks = userBookmarkMapper.getAllChildBookmarkTree(userId, bookmarkId);
            Set<String> set = new HashSet<>();
            getBookmarkIds(bookmarks, set);
            resultSet.addAll(set);
        }
        resultSet.remove(UserConstant.ROOT_BOOKMARK_ID);
        return new ArrayList<>(resultSet);
    }

    private void getBookmarkIds(List<UserBookmarkVo> bookmarks, Set<String> bookmarkIds) {
        if (bookmarks == null || bookmarks.size() == 0) {
            return;
        }
        for (UserBookmarkVo bookmark : bookmarks) {
            bookmarkIds.add(bookmark.getId());
            getBookmarkIds(bookmark.getChildren(), bookmarkIds);
        }
    }

    @Override
    public List<UserBookmarkVo> getAllChildBookmarkTree(String userId) {
        return userBookmarkMapper.getAllChildBookmarkTree(userId, UserConstant.ROOT_BOOKMARK_ID);
    }


    @Override
    public Result<Object> getUserListByParentUserId(LoginUser loginUser, QueryUserListParam queryUserListParam) throws Exception {
        Result<Object> result = userFeignController.getUserListByParentUserId(loginUser.getId(), queryUserListParam.getSearch(), queryUserListParam.getCurrentPageNum(), queryUserListParam.getEveryPageNum());
        return success(result.getResult());
    }


    @Override
    public BookMarkList getAllChildBookmarkTreeAndShare(String userId, LoginUser loginUser) {

        BookMarkList allBookMarkList = new BookMarkList();
        List<UserBookmarkVo> ownBookMarkList = userBookmarkMapper.getAllChildBookmarkTree(userId, UserConstant.ROOT_BOOKMARK_ID);
        allBookMarkList.setOwnBookMarkList(ownBookMarkList);
        if ("4".equals(loginUser.getRole())) {
            //根据当前用户的父账号UserId查询,查询出被分享的bookMark；
            if (loginUser.getUserParentId() != null) {
                String parentId = userBookmarkMapper.selectParentId(loginUser.getId());
                if (parentId != null) {
                    List<UserBookmarkVo> shareBookMarkList = userBookmarkMapper.getAllChildBookmarkTree(parentId, UserConstant.ROOT_BOOKMARK_ID);
                    allBookMarkList.setShareBookMarkList(shareBookMarkList);
                }
            }
        }
        return allBookMarkList;
    }

    @Override
    public List<UserBookmarkVo> getAllParentBookmarkTree(String userId, String bookmarkId) {
        return userBookmarkMapper.getParentBookmarkTree(userId, bookmarkId);
    }

    @Override
    @Transactional
    public int createBookmark(String userId, String parentId, String name) {
        UserBookmark record = new UserBookmark()
                .setUserId(userId)
                .setBookmarkName(name)
                .setParentId(parentId);
        List<UserBookmark> exist = userBookmarkMapper.select(record);
        if (!CollectionUtils.isEmpty(exist)) {
            // 书签名已存在
            return 1;
        }
        record.setParentId(parentId);
        record.setId(MyUtil.getUUID());
        userBookmarkMapper.insert(record);

        bookmarkDeviceService.setBookmarkDeviceToMem();
        return 0;
    }

    @Override
    @Transactional
    public int updateBookmark(String id, String name) {
        UserBookmark bookmark = userBookmarkMapper.selectByPrimaryKey(id);
        if (bookmark == null) {
            return 1;
        }
        UserBookmark record = new UserBookmark()
                .setUserId(bookmark.getUserId())
                .setBookmarkName(name)
                .setParentId(bookmark.getParentId());
        List<UserBookmark> exist = userBookmarkMapper.select(record);
        if (!CollectionUtils.isEmpty(exist)) {
            // 书签名已存在
            return 2;
        }
        bookmark.setBookmarkName(name);
        userBookmarkMapper.updateByPrimaryKeySelective(bookmark);

        bookmarkDeviceService.setBookmarkDeviceToMem();
        return 0;
    }

    @Override
    @Transactional
    public int deleteBookmark(String id) {
        UserBookmark userBookmark = this.getById(id);
        if (userBookmark == null) {
            return 1;
        }
        List<String> allChildBookmarkIds = this.getAllChildBookmarkIds(userBookmark.getUserId(), id);
        if (CollectionUtils.isEmpty(allChildBookmarkIds)) {
            return 1;
        }
        userBookmarkMapper.deleteBookmark(allChildBookmarkIds);
        bookmarkDeviceMapper.deleteBookmarkDevice(allChildBookmarkIds);
        bookmarkDeviceService.setBookmarkDeviceToMem();
        return 0;
    }

    @Override
    public UserBookmark getById(String bookmarkId) {
        return userBookmarkMapper.selectByPrimaryKey(bookmarkId);
    }

    @Override
    public void deleteUserAllBookmark(String userId) {
        List<String> bookmarkIds = userBookmarkMapper.listUserBookmarkId(userId);
        if (CollectionUtils.isEmpty(bookmarkIds)) {
            return;
        }
        bookmarkDeviceMapper.deleteBookmarkDevice(bookmarkIds);
        userBookmarkMapper.deleteBookmark(bookmarkIds);
    }


    @Override
    public Result<Object> updateBookMarkShareParam(LoginUser loginUser, UpdateBookMarkShareParam updateBookMarkShareParam) throws Exception {
        List<String> willAddUserIdList = updateBookMarkShareParam.getWillAddUserId();
        List<String> willRemoveUserIdList = updateBookMarkShareParam.getWillRemoveUserId();
        if ((willAddUserIdList == null || willAddUserIdList.size() == 0) && (willRemoveUserIdList == null || willRemoveUserIdList.size() == 0)) {
            return success();
        }
        //处理需要添加的用户id
        if (willAddUserIdList != null && willAddUserIdList.size() > 0) {
            //新增tvu_bookmark_share数据(批量插入)
            List<BookMarkShare> bookMarkShareList = new ArrayList<BookMarkShare>();
            for (String willAddUserId : willAddUserIdList) {
                if (org.springframework.util.StringUtils.isEmpty(willAddUserId)) {
                    continue;
                }
                String parentId = userBookmarkMapper.selectParentId(willAddUserId);
                if (parentId != null) {
                    ServerException.Exception(ResultConstant.BookMarkShare.BOOKMARK_ALREADY_SHARE);
                }
                bookMarkShareList.add(getBookMarkShare(0, loginUser.getId(), willAddUserId));

            }

            if (bookMarkShareList.size() > 0) {
                bookmarkDeviceMapper.saveBookMarkShareBatch(bookMarkShareList);
            }
        }
        //处理需要移除的用户id
        if (willRemoveUserIdList != null && willRemoveUserIdList.size() > 0) {
            for (String willRemoveUserId : willRemoveUserIdList) {
                if (org.springframework.util.StringUtils.isEmpty(willRemoveUserId)) {
                    continue;
                }
                //根据、子用户id、父用户id移除数据
                bookmarkDeviceMapper.deleteBookMarkShare(willRemoveUserId, loginUser.getId(), System.currentTimeMillis());
            }
        }
        return success();
    }


    private BookMarkShare getBookMarkShare(Integer deleteFlag, String parentUserId, String subUserId) {
        BookMarkShare bookShare = new BookMarkShare();

        bookShare.setId(IdGenerator.createId());
        bookShare.setCreateTime(System.currentTimeMillis());
        bookShare.setUpdateTime(System.currentTimeMillis());
        bookShare.setDeleteFlag(deleteFlag);
        bookShare.setParentUserId(parentUserId);
        bookShare.setSubUserId(subUserId);

        return bookShare;
    }


    @Override
    public List<AlreadyShareSonListVo> getAlreadyShareSonList(LoginUser loginUser) throws Exception {

        String userId = loginUser.getId();

        List<AlreadyShareSonListVo> alreadyShareSonList = bookmarkDeviceMapper.getAlreadyShareSonList(userId);

        return alreadyShareSonList;
    }


    @Override
    public Result<Object> getNoShareUserListByParentUserId( String userId, String search, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);

        List<LoginUser> allSonList = userMapper.getNoShareUserListByParentUserId( userId, search);
   /*     List<LoginUser> allSonList = userMapper.getUserListByParentUserId(userId,search);

        List<AlreadyShareSonListVo> alreadyShareSonList =bookmarkDeviceMapper.getAlreadyShareSonList(userId);

        }*/
        return ResultUtil.success(new PageInfo(allSonList));
    }

}
